<template>
  <DialogCom :draggable="true" :title="title" :width="'500'" :visible="isVisible" @close="close" @confirm="confirm">
    <template v-slot:content>
        <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="90px" class="demo-ruleForm"
          status-icon>
          <el-form-item label="文件:" prop="shp">
            <div class="path">
              <el-input v-model="formData.shp" placeholder="请上传SHP文件压缩包" disabled />
              <input v-show="false" ref="upfileRef" type="file" title=" " @change="upLoadFile" multiple="multiple"
                style="display: none" />
              <el-button class="common-btn" @click="selectFile">上传</el-button>
            </div>
          </el-form-item>
          <el-form-item label="名称字段:" prop="prop">
            <el-select v-model="formData.prop" placeholder="请先上传SHP文件再选择字段">
              <el-option v-for="(item, index) in selArr" :key="index" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="高程:" prop="height" v-if="type == 'HeightMask'">
            <el-input v-model="formData.height" type="number" :step="1" :min="0" @change="editHandle" />
          </el-form-item>


        </el-form>
    </template>
  </DialogCom>
</template>

<script setup>
import { ref, defineProps } from 'vue'
import DialogCom from '@/components/common/DialogCom.vue'
import { upShpZip, upShp, reqGetShpFeatures } from '@/api/terrainrtsApi'
import { ElMessage } from 'element-plus'
import loading from "@/api/loading"


// 上传文件
const upfileRef = ref(null)
let arr = []
let fromDataArr = []
const selArr = ref([])
const typeList = ref([{ label: '散列', value: 'file' }])
const ruleFormRef = ref('')
const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  close: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  type: {
    type: String,
    default: '',
  },
})
const emits = defineEmits(['close', 'confirm'])
const formData = ref({
  shp: '',
  prop: '',
  serverPath: '',
  features: '',
  height: 0,
})

const rules = ref({
  prop: [{ required: true, message: '请选择字段', trigger: 'blur' }],
  shp: [{ required: true, message: '请上传SHP文件压缩包', trigger: 'blur' }],
  height: [{ required: true, message: '请输入高程', trigger: 'blur' }],
})

const selectFile = () => {
  upfileRef.value.click()
}

const editHandle = (value) => {
  // 将输入值强制转换为数字，并确保不小于 0.1
  const numValue = Number(value);
  if (numValue <= 0 || isNaN(numValue)) {
    formData.value.height = 0
  }
}

const upLoadFile = async (e) => {
  const files = e.target.files
  if (files.length === 0) return
  Object.keys(files).forEach((key) => {
    arr.push(files[key].name)
  })
  formData.value.shp = arr.join(',')
  arr = []
  let filesData = new FormData()
  for (let i = 0; i <= files.length - 1; i++) {
    filesData.append('file', files[i])
  }
  if (files.length > 1) {
    try {
      const res = await upShp(filesData)

      if (res.code === 1000) {
        ElMessage.success('上传成功')
        if (res.code === 1000) {
          // let getFeatureData = new FormData()
          // getFeatureData.append('path', res.data)
          formData.value.serverPath = res.data
          const data = {
            "path": res.data
          }
          await getShpFeatures(data)
        }
      }
    } catch (error) {
      console.log(error)
    }
  } else {
    try {
      const res = await upShpZip(filesData)

      if (res.code == 1000) {
        ElMessage.success('上传成功')
        if (res.code === 1000) {
          // let getFeatureData = new FormData()
          // getFeatureData.append('path', res.data)
          formData.value.serverPath = res.data

          setTimeout(async () => {
            const data = {
              "path": res.data
            }
            await getShpFeatures(data)
          }, 200)
        }
      }
    } catch (error) {
      console.log(error)
    }
  }
}

const getShpFeatures = async (data) => {
  selArr.value = []
  formData.value.prop = ""
  try {
    const ret = await reqGetShpFeatures(data)
    console.log(ret.data);
    if (ret.code !== 1000) {
      loading.closeLoading()
      ElMessage({
        message: "获取失败",
        type: 'error',
      })
      return;
    }
    loading.closeLoading()
    ElMessage({
      message: "获取成功",
      type: 'success',
    })
    formData.value.features = ret.data;
    const prop = ret.data[0].prop
    Object.keys(prop).forEach((key) => {
      selArr.value.push(key)
    })
  } catch (error) {
    loading.closeLoading()
    console.log(error)
  }
}

const close = () => {
  emits('close')
}
// 确认
const confirm = () => {
  ruleFormRef.value.validate((valid) => {
    if (!valid) return
    emits('confirm', {
      path: formData.value.serverPath,
      nameField: formData.value.prop,
      features: formData.value.features,
      height: Number(formData.value.height)
    })
  })
}
</script>

<style scoped>

.el-form-item .el-textarea,
.el-form-item .el-select,
.el-form-item .el-input {
  width: 300px !important;
}

.item {
  width: 300px;
}

.path {
  display: grid;
  grid-template-columns: 300px 70px;
  grid-column-gap: 5px;
}
</style>
